package com.reborn.mall.api.controller;

import com.reborn.mall.api.model.entity.BaseEntity;
import com.reborn.mall.api.service.BaseService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * Controller 基类
 *
 * @author wu.yue
 * @since 2020/1/18
 */
public abstract class BaseController<T extends BaseEntity> {

    @Autowired
    private BaseService<T> baseService;

    @ApiOperation("获取指定ID的实体信息")
    @GetMapping("/{id}")
    public T get(@PathVariable("id") Long id) {
        return baseService.findById(id);
    }

    @ApiOperation("获取指定内容的实体信息")
    @PostMapping("/existsOne")
    public T getOne(@RequestBody T entity) {
        return baseService.findOne(entity);
    }

    @ApiOperation("获取所有实体的列表")
    @GetMapping
    public List<T> list(@ModelAttribute T entity) {
        return baseService.find(entity);
    }

    @ApiOperation("创建实体")
    @PostMapping
    public T insert(@RequestBody T entity) {
        return baseService.insertSelective(entity);
    }

    @ApiOperation("批量创建实体")
    @PostMapping("/batch")
    public int insertBatch(@RequestBody List<T> entities) {
        return baseService.insertBatch(entities);
    }

    @ApiOperation("更新指定ID的实体信息")
    @PutMapping("/{id}")
    public int update(@PathVariable("id") Long id, @RequestBody T entity) {
        entity.setId(id);
        return baseService.updateByIdSelective(entity);
    }

    @ApiOperation("删除指定ID的实体")
    @DeleteMapping("/{id}")
    public int delete(@PathVariable("id") Long id) {
        return baseService.deleteById(id);
    }
}
